package net.homeip.mmhg.game;

import java.util.StringTokenizer;

import org.springframework.stereotype.Service;

/**
 * Checks whether the answer is correct.
 *
 * @author ilya gerasimov
 */
@Service
public class AnswerChecker {
	
	public String checkAnswer(ObtainedTask task, String answer) {
		StringTokenizer tokenizer = new StringTokenizer(answer);
		StringBuilder result = new StringBuilder();
		int codesTotal = 0, wrongCodes = 0; 
		while (tokenizer.hasMoreTokens()) {
			String token = (String)tokenizer.nextElement();
			codesTotal++;
			int index = task.getAnswers().indexOf(token.toUpperCase()); 
			if (index != -1) {
				task.getAnswers().remove(index);
			} else {
				wrongCodes++;
				result.append(" " + token);
			}
		}
		
		if (wrongCodes == codesTotal) {
			return answer;
		} else {
			task.setGuessedCodes(task.getGuessedCodes() + (codesTotal - wrongCodes));
		}
		
		if (result.length() > 0) {
			return result.substring(0);
		} else {
			return null;
		}
		
	}
}
